package uml.example;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;


public class EventProcessor implements ActionListener {
	private GUI ownerGUI;
	private StringBuffer InputBuffer;  //
	private String preOperator;  		//tinh toan lan truoc
	private double preValue;
	private double memoryValue;
	private Boolean newDigit;
	public EventProcessor(GUI gui){
		ownerGUI = gui;		
	}
	
	//khởi tạo tính toán
	public void initCalculation(){
		InputBuffer = new StringBuffer();
		preOperator = "";
		preValue =0;
		memoryValue = 0;
		newDigit = true;
		ownerGUI.setDisplayField("0");
		
	}

	public void actionPerformed(ActionEvent evt) {
		// TODO Auto-generated method stub
		JButton b = (JButton)evt.getSource();
		String value = b.getText();
		if (value.equals("C")) initCalculation();
		else if (value.equals(".")||value.equals("0")||value.equals("1")||
				value.equals("2")||value.equals("3")||value.equals("4")||
				value.equals("5")||value.equals("5")||value.equals("7")||
				value.equals("8")||value.equals("9")) {
			if (newDigit) {
				InputBuffer = new StringBuffer();
				InputBuffer.append(value);
				ownerGUI.setDisplayField(value);
				newDigit =false;
				
			} else {
				InputBuffer.append(value);
				ownerGUI.setDisplayField(InputBuffer.toString());;

			}
			
		}else if(value.equals("+")||value.equals("-")||value.equals("*")||
				value.equals("/")||value.equals("=")||value.equals("M+")||
				value.equals("M-"))  {
			double currentValue =0;
			try {
				currentValue=(Double.valueOf(ownerGUI.getDisplayFieldText())).doubleValue();			
			} catch (NumberFormatException e) {
				InputBuffer.delete(0, InputBuffer.length());
				ownerGUI.setDisplayField(InputBuffer.toString());
				return;	
			}
			if (preOperator.equals("+")) preValue = preValue + currentValue;
			else if (preOperator.equals("-")) preValue = preValue - currentValue;
			else if (preOperator.equals("*")) preValue = preValue * currentValue;
			else if (preOperator.equals("/")) preValue = preValue / currentValue;
			else preValue = currentValue;
			if(value.equals("M+")){
				memoryValue = memoryValue + preValue;
				preOperator = "";
			}else if (value.equals("M-")) {
				memoryValue = memoryValue - preValue;
				preOperator = "";
			}else preOperator = value;
			ownerGUI.setDisplayField(Double.toString(preValue));
			newDigit = true;
		}else if (value.equals("MR")) {
			ownerGUI.setDisplayField(Double.toString(memoryValue));
			newDigit = true;
		}

	}

}
